package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.BeanConv;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RoleResourceMapper roleResourceMapper;
    @Autowired
    UserRoleMapper userRoleMapper;


    @Override
    public List<RoleVo> findRoleVoListInUserId(List<Long> userIds) {
        return roleMapper.findRoleVoListInUserId(userIds);
    }

    /**
     * 条件查询分页角色列表
     *
     * @param roleDto
     * @param pageNum
     * @param pageSize
     */
    @Override
    public PageResponse<RoleVo> findRolePage(RoleDto roleDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<List<RoleVo>> page = roleMapper.selectPage(roleDto);
        PageResponse<RoleVo> pageResponse = PageResponse.of(page, RoleVo.class);

        return pageResponse;


    }

    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);


    }

    @Override
    public Set<String> findCheckedResource(Long roleId) {
        Set<String> resource = roleResourceMapper.selectResourceNoByRoleId(roleId);
        return resource;
    }

    @Transactional
    @Override
    public Boolean updateRole(RoleDto roleDto) {
        //1.对象拷贝
        Role role = BeanUtil.toBean(roleDto, Role.class);
        //2.修改角色
        if (roleDto.getDataState().equals("1")) {
            if (selectUserIdByRoleId(role.getId())) {
                throw new RuntimeException("该角色已分配用户，不能禁用");
            }
        }

        roleMapper.updateByPrimaryKeySelective(role);
        //3.判断是否修改角色对应的资源数据
        if (ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())) {
            return true;
        }

        //4.删除原有的角色资源中间信息
        roleResourceMapper.deleteRoleResourceByRoleId(role.getId());
        //5.保存角色资源中间信息
        List<RoleResource> roleResourceList = Lists.newArrayList();
        Arrays.asList(roleDto.getCheckedResourceNos()).forEach(n -> {
                    RoleResource roleResource = RoleResource.builder()
                            .roleId(role.getId())
                            .resourceNo(n)
                            .dataState(SuperConstant.DATA_STATE_0)
                            .build();
                    roleResourceList.add(roleResource);
                }
        );
        //6.如果集合为空，则请求结束
        if (EmptyUtil.isNullOrEmpty(roleResourceList)) {
            return true;
        }
        //7.批量保存角色与资源的关系数据
        roleResourceMapper.batchInsert(roleResourceList);

        return true;
    }

    private boolean selectUserIdByRoleId(Long id) {
        int result = userRoleMapper.selectUserIdByRoleId(id);
        return result > 0 ? true : false;
    }

    /**
     * 删除角色
     *
     * @param roleId
     */
    @Override
    @Transactional
    public void deleteById(Long roleId) {
        //删除角色与菜单关联
        roleResourceMapper.deleteRoleResourceByRoleId(roleId);
        //删除角色基本信息
        roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public List<RoleVo> initRoles() {
        RoleVo roleVo = RoleVo.builder()
                .dataState(SuperConstant.DATA_STATE_0)
                .build();
        List<Role> roleList = roleMapper.selectList(roleVo);
        return BeanConv.toBeanList(roleList, RoleVo.class);
    }
}
